/**
 * 钉钉登录状态管理工具
 */

// 检查是否已登录
export function isLoggedIn() {
  const token = localStorage.getItem('dingtalk_token')
  const loginTime = localStorage.getItem('login_time')
  const expiresIn = localStorage.getItem('dingtalk_expires_in')
  
  if (!token || !loginTime || !expiresIn) {
    return false
  }
  
  // 检查token是否过期
  const now = Date.now()
  const loginTimestamp = parseInt(loginTime)
  const expiresInMs = parseInt(expiresIn) * 1000
  
  if (now - loginTimestamp > expiresInMs) {
    // token已过期，清除本地存储
    clearAuthData()
    return false
  }
  
  return true
}

// 获取用户信息
export function getUserInfo() {
  const userInfoStr = localStorage.getItem('user_info')
  if (!userInfoStr) {
    return null
  }
  
  try {
    // 先尝试直接解析 JSON
    return JSON.parse(userInfoStr)
  } catch (e) {
    // 如果失败，可能是 URL 编码的字符串，尝试先解码再解析
    try {
      const decoded = decodeURIComponent(userInfoStr)
      return JSON.parse(decoded)
    } catch (e2) {
      console.warn('解析用户信息失败:', e2)
      // 清除损坏的数据
      localStorage.removeItem('user_info')
      return null
    }
  }
}

// 获取访问token
export function getAccessToken() {
  return localStorage.getItem('dingtalk_token')
}

// 获取刷新token
export function getRefreshToken() {
  return localStorage.getItem('dingtalk_refresh_token')
}

// 清除认证数据
export function clearAuthData() {
  localStorage.removeItem('dingtalk_token')
  localStorage.removeItem('dingtalk_refresh_token')
  localStorage.removeItem('dingtalk_expires_in')
  localStorage.removeItem('user_info')
  localStorage.removeItem('login_time')
}

// 保存认证数据
export function saveAuthData(token, refreshToken, expiresIn, userInfo) {
  localStorage.setItem('dingtalk_token', token)
  localStorage.setItem('dingtalk_refresh_token', refreshToken || '')
  localStorage.setItem('dingtalk_expires_in', expiresIn || '1800')
  localStorage.setItem('user_info', JSON.stringify(userInfo || {}))
  localStorage.setItem('login_time', Date.now().toString())
}

// 刷新token
export async function refreshAccessToken() {
  const refreshToken = getRefreshToken()
  if (!refreshToken) {
    throw new Error('没有刷新token')
  }
  
  try {
    const response = await fetch('http://localhost:8000/user/dingtalk/refresh-token', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        refresh_token: refreshToken
      })
    })
    
    if (!response.ok) {
      throw new Error('刷新token失败')
    }
    
    const data = await response.json()
    
    // 更新本地存储
    if (data.data && data.data.access_token) {
      saveAuthData(
        data.data.access_token,
        data.data.refresh_token,
        data.data.expires_in,
        getUserInfo()
      )
      return data.data.access_token
    }
    
    throw new Error('刷新token响应格式错误')
  } catch (error) {
    console.error('刷新token失败:', error)
    clearAuthData()
    throw error
  }
}

// 登出
export function logout() {
  clearAuthData()
  // 可以在这里添加其他登出逻辑，比如通知后端等
}

